<?php


namespace app\agent\service;

class MemberAppService
{
	public static function get_card_list($options)
	{
		$where = [];
		$where[] = ["appid", "=", $options["appid"]];
		$where[] = ["agent_id", "=", $options["agent_id"]];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["batch_number"]) && $options["batch_number"] != "") {
			$batch = \think\Db::name("app_member_card_batch")->where([["agent_id", "=", $options["agent_id"]], ["number", "like", "%{$options["batch_number"]}%"]])->find();
			if (!empty($batch)) {
				$where[] = ["batch_id", "=", $batch["id"]];
			}
		} else {
			if (isset($options["batch_id"]) && $options["batch_id"] != "") {
				$where[] = ["batch_id", "=", $options["batch_id"]];
			}
		}
		if (isset($options["type"]) && $options["type"] != "") {
			$where[] = ["type", "=", $options["type"]];
		}
		if (isset($options["time_type"]) && $options["time_type"] != "") {
			$where[] = ["time_type", "=", $options["time_type"]];
		}
		if (isset($options["time_value"]) && $options["time_value"] != "") {
			$where[] = ["time_value", "=", $options["time_value"]];
		}
		if (isset($options["status"]) && $options["status"] != "") {
			$where[] = ["status", "=", $options["status"]];
		}
		if (isset($options["useuid"]) && $options["useuid"] != "") {
			$where[] = ["useuid", "=", $options["useuid"]];
		}
		if (isset($options["card"]) && $options["card"] != "") {
			// 使用 BINARY 关键字实现区分大小写的模糊查询
			$where[] = ["", "exp", \think\Db::raw("BINARY `card` LIKE '%" . addslashes($options["card"]) . "%'")];
		}
		$list = \think\Db::name("app_member_card")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_member_card")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$data[] = self::get_array_info($item);
		}
		return ["code" => \app\agent\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function get_array_info($item)
	{
		return $item;
	}
	public static function get_card_info($options)
	{
		$item = \think\Db::name("app_member_card")->where(["id" => $options["id"], "appid" => $options["appid"], "agent_id" => $options["agent_id"]])->find();
		if (empty($item)) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "id不存在"];
		}
		return ["code" => \app\agent\model\Code::success, "data" => self::get_array_info($item)];
	}
	public static function add_card($options)
	{
		$num = $options["num"];
		if (\app\common\server\ConfigServer::get("system", \app\common\model\DefaultConfig::SystemTestDemoField, false) && $num > 2) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "当前站点为演示站点,一次最多只能生成2个" . \app\common\model\DefaultConfig::SystemTestDemoTipsSuffixText];
		}
		$isSystemAuthUnpaid = isSystemAuthUnpaid();
		if ($isSystemAuthUnpaid && \app\common\model\FreeQuota::MemberAddCardLimitNum < $num) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,一次最多只能生成" . \app\common\model\FreeQuota::MemberAddCardLimitNum . ",您可分多次生成" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		if ($isSystemAuthUnpaid && \think\Db::name("app_member_card")->where(["appid" => $options["appid"]])->count() + $num > \app\common\model\FreeQuota::MemberAppCardQuota) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,一个应用最多只能存储" . \app\common\model\FreeQuota::MemberAppCardQuota . "个卡密" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		$today = \think\helper\Time::today();
		if ($isSystemAuthUnpaid && \think\Db::name("app_member_card")->where([["appid", "=", $options["appid"]], ["addtime", "between", $today]])->count() + $num > \app\common\model\FreeQuota::MemberAppDailyAddCard) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,一个应用每天最多只能生成" . \app\common\model\FreeQuota::MemberAppDailyAddCard . "个卡密" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		if ($isSystemAuthUnpaid && \think\Db::name("app")->count() > \app\common\model\FreeQuota::AppQuota) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,最多只能拥有" . \app\common\model\FreeQuota::AppQuota . "个应用" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		\think\Db::startTrans();
		try {
			$card_type = $options["time_type"] ?? 0;
			if ($options["type"] === 1) {
				$card_type = "point";
			} elseif ($options["type"] === 2) {
				$card_type = "register_code";
			}
			$app = \think\Db::name("app")->where("id", $options["appid"])->find();
			$agent = \think\Db::name("app_agent")->where("id", $options["agent_id"])->find();
			$agent_config = json_decode($app["agent_config"], true);
			$authority_config = AgentService::get_agent_authority_config($app, $agent);
			$addCardLimitHandle = AgentService::addCardLimitHandle($agent_config, $authority_config, $options["time_value"] ?? 0, $card_type, $num);
			if ($addCardLimitHandle !== true) {
				return ["code" => \app\agent\model\Code::fail, "msg" => $addCardLimitHandle["msg"]];
			}
			$binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"]])->find();
			if (empty($binding)) {
				throw new \Exception("您不是该应用的代理关系");
			}
			if (!AgentService::checkSuperiorPrice($app, $agent, $binding)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "上级价格变动差异,请联系上级更新当前应用绑定的价格"];
			}
			if ($options["type"] === \app\common\model\CardType::Time[0]) {
				if (!isset($authority_config["price"][$card_type]) || !$authority_config["price"][$card_type]) {
					return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,当前卡类型的代理价格为空(未设置价格)无法计费不允许生成"];
				}
				if ($card_type != 6) {
					$price = $authority_config["price"][$card_type] * $options["value"] * $options["num"];
				} else {
					$price = $authority_config["price"][$card_type] * 1 * $options["num"];
				}
			} elseif ($options["type"] === \app\common\model\CardType::Point[0]) {
				$price = $authority_config["price"][$card_type] * $options["value"] * $options["num"];
			} elseif ($options["type"] === \app\common\model\CardType::RegisterCode[0]) {
				$price = $authority_config["price"][$card_type] * 1 * $options["num"];
			}
			if ($agent["money"] < $price) {
				return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,可用余额不足"];
			}
			if ($price <= 0) {
				return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,价格计费异常"];
			}
			$batch_number = uniqid();
			$batch_id = \think\Db::name("app_member_card_batch")->insertGetId(["appid" => $app["id"], "agent_id" => $agent["id"], "time" => time(), "num" => $options["num"], "number" => $batch_number, "remarks" => $options["batch_remarks"] ?? "", "card_type" => $options["type"] ?? 0, "card_time_type" => $options["time_type"] ?? 0, "card_value" => $options["value"] ?? 1]);
			$list = getAgentAddCardStructure($app, $authority_config, $num, $card_type);
			foreach ($list as $card) {
				\think\Db::name("app_member_card")->insert(["appid" => $options["appid"], "agent_id" => $options["agent_id"], "type" => $options["type"], "time_type" => $options["time_type"] ?? 0, "value" => $options["value"] ?? 1, "addtime" => time(), "card" => $card, "batch_id" => $batch_id]);
			}
			\app\common\AppAgent::money($agent, $price, 1, "生成卡密{$options["num"]}个,应用ID {$app["id"]},批次号 {$batch_number}");
			AgentService::addCardGiveDisparityPriceSuperior($app, $agent, $binding, $card_type, $options["value"] ?? 1, $options["num"]);
			\think\Db::commit();
			return ["code" => \app\agent\model\Code::success, "data" => ["list" => $list, "string" => implode("\n", $list), "batch" => ["id" => $batch_id, "number" => $batch_number]], "msg" => "生成成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\agent\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_card_batch_list($options)
	{
		$where = [];
		$where[] = ["appid", "=", $options["appid"]];
		$where[] = ["agent_id", "=", $options["agent_id"]];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["number"]) && $options["number"] != "") {
			$where[] = ["number", "like", "%" . $options["number"] . "%"];
		}
		if (isset($options["remarks"]) && $options["remarks"] != "") {
			$where[] = ["remarks", "like", "%" . $options["remarks"] . "%"];
		}
		if (isset($options["keyword"]) && $options["keyword"] != "") {
			$where[] = ["", "exp", \think\Db::raw("remarks like '%{$options["keyword"]}%' or number like '%{$options["keyword"]}%'")];
		}
		$list = \think\Db::name("app_member_card_batch")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_member_card_batch")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$item["card_info"] = ["total" => \think\Db::name("app_member_card")->where(["batch_id" => $item["id"]])->count(), "used_total" => \think\Db::name("app_member_card")->where(["status" => 1, "batch_id" => $item["id"]])->count(), "not_used_total" => \think\Db::name("app_member_card")->where(["status" => 0, "batch_id" => $item["id"]])->count()];
			$data[] = $item;
		}
		return ["code" => \app\agent\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages, "all_card_data" => ["total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"]])->count(), "used_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "status" => 1])->count(), "not_used_total" => \think\Db::name("app_member_card")->where(["status" => 0, "appid" => $options["appid"], "agent_id" => $options["agent_id"]])->count(), "minute_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 0, "type" => \app\common\model\CardType::Time[0]])->count(), "hour_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 1, "type" => \app\common\model\CardType::Time[0]])->count(), "day_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 2, "type" => \app\common\model\CardType::Time[0]])->count(), "week_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 3, "type" => \app\common\model\CardType::Time[0]])->count(), "month_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 4, "type" => \app\common\model\CardType::Time[0]])->count(), "quarter_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 7, "type" => \app\common\model\CardType::Time[0]])->count(), "half_year_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 8, "type" => \app\common\model\CardType::Time[0]])->count(), "year_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 5, "type" => \app\common\model\CardType::Time[0]])->count(), "perpetual_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "time_type" => 6, "type" => \app\common\model\CardType::Time[0]])->count(), "point_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "type" => \app\common\model\CardType::Point[0]])->count(), "register_code_total" => \think\Db::name("app_member_card")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"], "type" => \app\common\model\CardType::RegisterCode[0]])->count()]];
	}
	public static function export_member_card_table($options)
	{
		$result = MemberAppService::get_card_list($options);
		if ($result["code"] == \app\agent\model\Code::success) {
			$list = $result["data"];
			if (empty($list)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "=>无数据导出"];
			}
			$data[] = ["ID", "卡密", "类型", "时长类型", "面值", "状态", "生成时间", "使用时间", "使用用户ID", "批次ID"];
			foreach ($list as $item) {
				$row = [$item["id"], $item["card"], \app\common\model\CardType::getName($item["type"]), \app\common\model\CardTimeType::getName($item["time_type"]), $item["value"], $item["status"] == 1 ? "已使用" : "未使用", date("Y-m-d H:i:s", $item["addtime"]), $item["usetime"] ? date("Y-m-d H:i:s", $item["usetime"]) : "", $item["useuid"], $item["batch_id"]];
				$data[] = $row;
			}
			unset($list);
			$res = \app\common\server\Export::export($options["export_file_type"], "充值卡卡密导出_" . date("Y-m-d H:i:s"), $data, 1);
			return ["code" => \app\agent\model\Code::success, "msg" => "文件生成完成", "data" => \app\system\service\ExportService::export_return_data_structure($res)];
		} else {
			return $result;
		}
	}
}